/*
 * @Description:
 * @Author: LCL
 * @Date: 2021-11-26
 * @LastEditors: LCL
 * @LastEditTime: 2021-12-02
 * @FilePath: /beff/src/components/drag/FrontEndEvent/useInputCursor.ts
 */

import { Input } from 'antd';
import { useRef } from 'react';
/**
 * 支持antd Input 光标操作
 */
export function useInputCursor() {
  // ant design component ref
  const ref = useRef(null);
  // dom 中的元素对象
  let domRef: any;
  const submitValue = '';
  const setRef = (target: any) => {
    ref.current = target;
    if (!target) {
      domRef = null;
      return;
    }
    // domRef = ref.current;
    if (target instanceof Input) {
      domRef = (ref.current as any).input as any;
    } else {
      domRef = (ref.current as any).resizableTextArea.textArea as any;
    }
  };

  const getSubmitValue = () => {
    return submitValue;
  };

  /** 获取光标所在位置 */
  const getCursorPos = () => {
    // 获取光标位置
    const CaretPos = {
      start: 0,
      end: 0,
    };
    if (domRef.selectionStart) {
      // Firefox support
      CaretPos.start = domRef.selectionStart;
    }
    if (domRef.selectionEnd) {
      CaretPos.end = domRef.selectionEnd;
    }
    return CaretPos;
  };

  /** 设置光标位置，不支持区间 */
  const setCursorPos = (pos: number) => {
    domRef.focus();
    domRef.setSelectionRange(pos, pos);
  };
  // const savedRange: Range | null = null;

  // const handleSelectionChange = () => {
  //   const sel = window.getSelection && window.getSelection();
  //   if (sel && sel.rangeCount) {
  //     savedRange = sel.getRangeAt(0);
  //   }
  // };

  // document.addEventListener('selectionchange', handleSelectionChange, false);

  // const keepCursorEnd = (isReturn) => {
  //   // const div = document.getElementById('edit');
  //   if (window.getSelection) {
  //     // ie11 10 9 firefox safari
  //     domRef.focus();
  //     const sel = window.getSelection(); // 创建range
  //     sel!.selectAllChildren(domRef); // range 选择obj下所有子内容
  //     sel!.collapseToEnd(); // 光标移至最后
  //     if (isReturn) return sel;
  //   }
  // };

  // const insertAt = (str: string) => {
  //   let sel, range;

  //   const tag = `<input
  //     class="ant-tag ant-tag-blue"
  //     type="button"
  //     value=${str}
  //   />`;
  //   // IE9 and non-IE
  //   if (window.getSelection) {
  //     sel = window.getSelection();
  //     if (sel && sel.rangeCount === 0 && savedRange !== null) sel.addRange(savedRange); // 保留光标在文字中间插入的最后位置
  //     if (sel && sel.rangeCount) range = sel.getRangeAt(0);
  //     if (['', null, undefined].includes(range)) {
  //       // 如果div没有光标，则在div内容末尾插入
  //       range = keepCursorEnd(true).getRangeAt(0);
  //     } else {
  //       const contentRange = document.createRange();
  //       contentRange.selectNode(domRef);
  //       // 对比range，检查光标是否在输入范围内
  //       const compareStart = range.compareBoundaryPoints(Range.START_TO_START, contentRange);
  //       const compareEnd = range.compareBoundaryPoints(Range.END_TO_END, contentRange);
  //       const compare = compareStart !== -1 && compareEnd !== 1;
  //       if (!compare) range = keepCursorEnd(true).getRangeAt(0);
  //     }
  //     const input = range.createContextualFragment(tag);
  //     const lastNode = input.lastChild; // 记录插入input之后的最后节点位置
  //     range.insertNode(input);
  //     if (lastNode) {
  //       // 如果有最后的节点
  //       range = range.cloneRange();
  //       range.setStartAfter(lastNode);
  //       range.collapse(true);
  //       sel!.removeAllRanges();
  //       sel!.addRange(range);
  //     }
  //   }
  // };

  /** 在某一个位置插入字符串， 不支持区间 */
  const insertAt = (pos: number, str: string) => {
    const originValue: string = domRef.value;
    let value = '';
    if (!originValue) {
      // value = `$\{${optionsObj[str]}}`;
      value = `$\{${str}}`;
    } else {
      const newPos = Math.min(Math.max(0, pos), originValue.length);
      if (originValue.length <= newPos) {
        // value = originValue + `$\{${optionsObj[str]}}`;
        value = originValue + `$\{${str}}`;
      } else {
        // value = originValue.substr(0, newPos) + `$\{${optionsObj[str]}}` + originValue.substr(newPos);
        value = originValue.substr(0, newPos) + `$\{${str}}` + originValue.substr(newPos);
      }
    }
    domRef.value = value;
    setCursorPos(pos + str.length + 3);
    if ((ref.current as any) instanceof Input) {
      (ref.current as any).props.onChange({
        target: { value: domRef.value },
        currentTarget: { value: domRef.value },
      });
    } else {
      (ref.current as any).resizableTextArea.props.onChange({
        target: { value: domRef.value },
        currentTarget: { value: domRef.value },
      });
    }

    domRef.focus();
  };

  return { setRef, getSubmitValue, getCursorPos, insertAt };
}
